package com.ct.lotterysystem.service.activitystatus.operator;

import com.ct.lotterysystem.dao.dataobject.ActivityDO;
import com.ct.lotterysystem.dao.mapper.ActivityMapper;
import com.ct.lotterysystem.dao.mapper.ActivityPrizeMapper;
import com.ct.lotterysystem.service.dto.ConvertActivityStatusDTO;
import com.ct.lotterysystem.service.enums.ActivityPrizeStatusEnum;
import com.ct.lotterysystem.service.enums.ActivityStatusEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class ActivityOperator extends AbstractActivityOperator{

    @Autowired
    private ActivityMapper activityMapper;
    @Autowired
    private ActivityPrizeMapper activityPrizeMapper;
    @Override
    public Integer sequence() {
        return 2;
    }

    @Override
    public Boolean needConvert(ConvertActivityStatusDTO convertActivityStatusDTO) {

        Long activityId = convertActivityStatusDTO.getActivityId();
        ActivityStatusEnum targetStatus = convertActivityStatusDTO.getTargetActivityStatus();

        if (null == targetStatus
                || null == activityId) {
            return false;
        }

        ActivityDO activityDO = activityMapper.selectById(activityId);

        if (null == activityDO) {
            return false;
        }

        // 当前活动状态是否与传入状态一致
        if (targetStatus.name().equalsIgnoreCase(activityDO.getStatus())) {
            return false;
        }

        // 需要判断奖品是否全部抽完
        // 查询 INIT 状态的奖品个数
        int count = activityPrizeMapper.countPrize(activityId, ActivityPrizeStatusEnum.INIT.name());
        if (count > 0) {
            return false;
        }

        return true;
    }

    @Override
    public Boolean convert(ConvertActivityStatusDTO convertActivityStatusDTO) {

        Long activityId = convertActivityStatusDTO.getActivityId();
        ActivityStatusEnum targetStatus = convertActivityStatusDTO.getTargetActivityStatus();
        try {
            activityMapper.updateStatus(activityId, targetStatus.name());
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
